package mobilesearch.thread;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.content.pm.PackageInfo;
import java.util.List;
import java.util.ArrayList;
import mobilesearch.data.AppData;
import mobilesearch.ui.BroadcastCommand;
import android.content.pm.PackageManager;

public class AppSearchThread extends Thread {

	private static final String TAG = "AppSearchThread";
	private ContentResolver resolver;
	private Context context;

	private String appName;
	private String appVersion;
	private String appSize;

	public AppSearchThread(Context context, ContentResolver resolver) {
		super();
		this.context = context;
		this.resolver = resolver;

	}

	@Override
	public void run() {
		super.run();
		Log.i(TAG, "run()");
		
		ArrayList<AppData> appList = new ArrayList<AppData>();
		
		List<PackageInfo> packList = context.getPackageManager().getInstalledPackages(PackageManager.GET_UNINSTALLED_PACKAGES);
		int size = packList.size();
		Log.i(TAG, String.valueOf(size));
		for(int i = 0; i < size; i++){
		
			try{
				PackageInfo packInfo = packList.get(i);

				appName = packInfo.applicationInfo.loadLabel(context.getPackageManager()).toString();
				appVersion = packInfo.versionName;
				
				AppData data = new AppData();
				
				data.setAppName(this.appName);
				Log.i(TAG, appName);
				
				data.setAppVersion(this.appVersion);
				Log.i(TAG, appVersion);
				
				appList.add(data);
			}catch(Exception exception){
				Log.i(TAG, exception.toString());
			}

		}
		
		//broadcast the app data
		if(!appList.isEmpty()){
			Intent appIntent = new Intent(BroadcastCommand.SEARCH_APP);
			appIntent.putParcelableArrayListExtra(BroadcastCommand.SEARCH_APP, appList);
			this.context.sendBroadcast(appIntent);	
		}
	}
}
